package tw.cating.karmasaver;


import java.io.IOException;

import tw.cating.Utility.ADUtility;
import tw.cating.karmasaver.alarm.alarmActivity;
import tw.cating.karmasaver.intef.dataChangedListener;
import tw.cating.karmasaver.intef.finishListener;
import tw.cating.karmasaver.plurk.plurkApi;
import tw.cating.karmasaver.rss.EditRssActivity;
import tw.cating.karmasaver.rss.rssAdapter;
import tw.cating.karmasaver.rss.structer.rssNode;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class mainActivity extends Activity implements dataChangedListener{
	/** Called when the activity is first created. */
	rssAdapter mAdapter = null;
	ListView rssList = null;
	
	private Thread mAuthThread;
	private plurkApi plurk= null;
	Context mContext = null;
	Button btn_EditRss = null;
	
	private String mUsername = "";
	private String mPassword = "";
	
	Thread mADThread = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.main);
        
        plurk = new plurkApi(this);
		
		WebView adView = (WebView)findViewById(R.id.ad_view);
		mADThread = ADUtility.prepareADWebView(this, adView); 
		
		TextView v = (TextView)findViewById(R.id.hint);
		v.setVisibility(View.VISIBLE);
		
		rssList = (ListView)findViewById(R.id.rsslist);
		rssList.setVisibility(View.GONE);
    }
    

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (plurk != null) {
			plurk.finish();
		}
	}
    
    @Override
    protected Dialog onCreateDialog(int id) {
        final ProgressDialog dialog = new ProgressDialog(this);
        if (id == 0)
        	dialog.setMessage(mContext.getResources().getString(R.string.login));
        else if (id == 1)
        	dialog.setMessage(mContext.getResources().getString(R.string.post));
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                if (mAuthThread != null) {
                    mAuthThread.interrupt();
                    finish();
                }
            }
        });
        return dialog;
    }

	public void onFinishLogin(int result) {
		// TODO Auto-generated method stub
		if (result != plurkApi.LOGINRESULT_SUCCESSED) {
			Toast.makeText(mContext, R.string.login_activity_failed, Toast.LENGTH_LONG)
			.show();
			finish();
		}
		
    	dismissDialog(0);
    	
        mAdapter = new rssAdapter(this, this);
        
        rssList.setAdapter(mAdapter);
        rssList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position,	long id) {
				// TODO Auto-generated method stub
				rssNode rss = (rssNode)mAdapter.getItem(position);
				String msg = rss.getShorternLink() + " (" + rss.getDescription() + ")";
				plurk.requestPost(msg, new finishListener() {
					
					public void onFinish(int result) {
						// TODO Auto-generated method stub
						if (result == plurkApi.POSTRESULT_SUCCESSED) {
							Toast.makeText(mContext, "post to plurk successed", Toast.LENGTH_LONG)
							.show();
//							finish();
						} else {
							Toast.makeText(mContext, "post to plurk failed", Toast.LENGTH_LONG)
							.show();
						}
						dismissDialog(1);
					}
				});
				showDialog(1);
			}
		});
        
        btn_EditRss = (Button)findViewById(R.id.btn_editrss);
        btn_EditRss.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final Intent intent = new Intent(mContext, EditRssActivity.class);
				startActivity(intent);
			}
		});
        
        Button btn_addAlarm = (Button)findViewById(R.id.btn_checknew);
        btn_addAlarm.setText(R.string.setalarm);
        btn_addAlarm.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final Intent intent = new Intent(mContext, alarmActivity.class);
				startActivity(intent);
			}
		});
	}
	
	protected void LoginInfoReady() {
        mAuthThread = plurk.requestLogin(mUsername, mPassword, new finishListener() {

			public void onFinish(int result) {
				// TODO Auto-generated method stub
				onFinishLogin(result);
			}
        	
        });	
	}
	
	public static final int MSG_PREPARELOGININFOSUCCESSED = 1;
	public static final int MSG_ADDACCOUNTSUCCESSED = 2;
	
	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_PREPARELOGININFOSUCCESSED:
				LoginInfoReady();
				break;
			case MSG_ADDACCOUNTSUCCESSED:
				Thread t = new Thread() {
					public void run() {
						AccountManager am = AccountManager.get(mainActivity.this);
				        Account[] accs = am.getAccountsByType(Constants.ACCOUNT_TYPE);
			        	Account acc = accs[0];
			        	mUsername = acc.name;
			        	accountManagerFuture = am.getAuthToken(acc, Constants.AUTHTOKEN_TYPE, null, (Activity)mContext, null, null);
			        	try {
							Bundle authTokenBundle = accountManagerFuture.getResult();
							mPassword = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
							mHandler.sendEmptyMessage(MSG_PREPARELOGININFOSUCCESSED);
						} catch (OperationCanceledException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (AuthenticatorException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}		
					}
				};
				t.start();
				break;
				
			}
			super.handleMessage(msg);
		}
		
	};

	AccountManagerFuture<Bundle> accountManagerFuture = null;
	
	protected void prepareLogin() {
		final AccountManager am = AccountManager.get((Activity)mContext);
        final Account[] accs = am.getAccountsByType(Constants.ACCOUNT_TYPE);
        

		final Runnable run = new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
		        if (accs.length == 0) {
       	
		        	accountManagerFuture =
		        		am.addAccount(Constants.ACCOUNT_TYPE, Constants.AUTHTOKEN_TYPE, null, null, mainActivity.this, new AccountManagerCallback<Bundle>() {

							public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
								// TODO Auto-generated method stub
								mHandler.sendEmptyMessage(MSG_ADDACCOUNTSUCCESSED);
							}
		        			
		        		}, null);
		        } else {
		        	mHandler.sendEmptyMessage(MSG_ADDACCOUNTSUCCESSED);	
		        }
			}
			
		};
		
        final Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    run.run();
                } finally {

                }
            }
        };
        t.start();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (plurk.isLogined() == false && accountManagerFuture == null) {
			showDialog(0);
			prepareLogin();
		}
		
		if (mAdapter != null)
			mAdapter.reflash();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	        finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}


	public void onDataChanged() {
		// TODO Auto-generated method stub
		TextView v = (TextView)findViewById(R.id.hint);
		v.setVisibility(View.GONE);
		
		rssList.setVisibility(View.VISIBLE);
	}
}